// src/stores/cart.ts
import { defineStore } from 'pinia'

// 1. 把原来组件里那份 Dish 拷过来
export interface Dish {
  id: number
  name: string
  price: number
  stock: number
  image_url?: string
  category_id: number
}

export interface CartItem {
  dishId: number
  name: string
  price: number
  quantity: number
}

export const useCartStore = defineStore('cart', {
  state: () => ({ items: [] as CartItem[] }),
  getters: {
    totalAmount: state =>
      state.items.reduce((sum, i) => sum + i.price * i.quantity, 0),
    quantityOf: state => (dishId: number) =>
      state.items.find(i => i.dishId === dishId)?.quantity ?? 0
  },
  actions: {
    increment(dish: Dish) {          // 现在本地就能找到 Dish
      const idx = this.items.findIndex(i => i.dishId === dish.id)
      if (idx >= 0) {
        if (this.items[idx].quantity < dish.stock) {
          this.items[idx].quantity += 1
        }
      } else {
        this.items.push({
          dishId: dish.id,
          name: dish.name,
          price: dish.price,
          quantity: 1
        })
      }
    },
    decrement(dishId: number) {
      const idx = this.items.findIndex(i => i.dishId === dishId)
      if (idx === -1) return
      const item = this.items[idx]
      item.quantity -= 1
      if (item.quantity <= 0) this.items.splice(idx, 1)
    },
    clear() {
      this.items = []
    }
  }
})